<template>
  <div id="lyric">
    <p class="lyric_item" v-for="(item, i) in currentLyric" :key="i">
      {{ item }}
    </p>
  </div>
</template>

<script>
import Base64 from '../../../../utils/base64'
import { mapState } from 'vuex'

export default {
  name: 'lyric',
  data() {
    return {
      lyric: null
    }
  },
  props: [ 'songid', 'currentTime' ],
  created() {
    if(this.playing){
      this.getLyric(this.song.id)
    }
  },
  methods: {
    getLyric(id) {
      this.$store.dispatch('getLyric', id).then(res => {
        this.lyric = Base64.decode(res.data.lyric)
                          .split('[')
                          .slice(5)
                          .map(str => {
                            let t = str.split(']')
                            return {[t[0]]: t[1]}
                          })
                          .reduce((a, b) => {
                            return {...a, ...b}
                          })
        // console.log(this.lyric)
      })
    }
  },
  watch: {
    songid(id) {
      this.getLyric(id)
    }
  },
  computed: {
    currentLyric() {
      if(this.lyric !== null) {
        const that = this
        const pastLyric = []
        let i = 0
        Object.keys(this.lyric).forEach(key => {
          if(key.split(':')
              .reduce( (a, b) => 
                parseInt(a) * 60 * 100 + 
                  b.split('.')
                    .reduce( (a, b) => 
                      parseInt(a) * 100 + parseInt(b)
                    ) ) - 120 <= that.currentTimeStamp
            ) {
              if(that.lyric[key] !== '\n')  {
                pastLyric.push(that.lyric[key])
              }
            } else if ( i<=1 && that.lyric[key] !== '\n' ) {
              pastLyric.push(that.lyric[key])
              i++
            }
        })
        return pastLyric.slice(pastLyric.length - 4, pastLyric.length - 1)
      }
    },
    currentTimeStamp() {
      let t = this.currentTime.split(':')
      return ( parseInt(t[0]) * 60 + parseInt(t[1]) ) * 100
    },
    ...mapState({
      playing: state => state.PlayService.playing,
      song: state => state.PlayService.song
    })
  }
}
</script>

<style lang="less" scoped>
  #lyric {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .lyric_item {
      text-align: center;
      font-size: 16px;
      color: #000;
    }
    .lyric_item:first-child,
    .lyric_item:last-child {
      font-size: 14px;
      color: #4d4d4d;
    }
  }
</style>
